package com.mobileagri.backoffice.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.support.DataAccessUtils;
import org.springframework.stereotype.Repository;

import com.mobileagri.backoffice.model.AbstractObject;
import com.mobileagri.backoffice.model.Contact;

/**
 * Romain LOUVET TEST Contact DAO class.
 * 
 * @author LOUVET Romain
 * @param <E>
 */
@Repository
public class ContactDAO<E> extends AbstractDAO implements IDAO {

	/**
	 * Get List of contacts from database
	 * 
	 * @return list of all contacts
	 */
	@SuppressWarnings("unchecked")
	public List<E> getAll(int start, int limit) {

		List<Contact> listContact = new ArrayList<Contact>();
		List<Object> listObject = super.getObjects(new Contact(), start, limit);
		for (Object o : listObject) {
			listContact.add((Contact) o);
		}

		return (List<E>) listContact;
	}

	/**
	 * Get List of contacts from database
	 * 
	 * @return list of all contacts
	 */
	@SuppressWarnings("unchecked")
	public List<E> getAll() {

		// DetachedCriteria criteria = DetachedCriteria.forClass(Contact.class);

		String sqlQuery = " from Contact";

		return (List<E>) getHibernateTemplate().find(sqlQuery);
	}

	/**
	 * Delete a contact with the id passed as parameter
	 * 
	 * @param id
	 */
	public void delete(int id) {
		super.delete(new Contact(), id);
	}

	/**
	 * Create a new Contact on the database or Update contact
	 * 
	 * @param contact
	 * @return contact added or updated in DB
	 */
	public AbstractObject save(AbstractObject o) {
		Contact contact = (Contact) o;
		return (Contact) super.save(contact);
	}

	/**
	 * Get total of Contacts from database
	 * 
	 * @return
	 */
	public int getTotal() {
		return DataAccessUtils.intResult(getHibernateTemplate().find(
				"SELECT COUNT(*) FROM Contact"));
	}

}
